package com.coderush.admin.sys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coderush.admin.core.common.MyBatisPlusPageUtils;
import com.coderush.admin.core.common.PageResult;
import com.coderush.admin.core.component.SnowflakeIdGenerator;
import com.coderush.admin.core.utils.BeanConvertUtil;
import com.coderush.admin.core.utils.UserContext;
import com.coderush.admin.sys.dao.CompanyDao;
import com.coderush.admin.sys.exception.CompanyException;
import com.coderush.admin.sys.model.dto.CompanyAddDto;
import com.coderush.admin.sys.model.dto.CompanyUpdateDto;
import com.coderush.admin.sys.model.entity.Company;
import com.coderush.admin.sys.model.vo.CompanyPageVo;
import com.coderush.admin.sys.model.vo.CompanySimpleVo;
import com.coderush.admin.sys.model.vo.CompanyVo;
import com.coderush.admin.sys.service.CompanyService;
import com.coderush.admin.sys.mapper.CompanyMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author Administrator
* @description 针对表【sys_company(公司表)】的数据库操作Service实现
* @createDate 2025-08-17 21:19:03
*/
@Slf4j
@Service
@Transactional
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company>  implements CompanyService{

    @Resource
    private SnowflakeIdGenerator snowflakeIdGenerator;

    @Resource
    private CompanyDao companyDao;


    /**
     * 查询公司列表
     * 用于添加/修改角色时的公司下拉列表框
     *
     * @return
     */
    @Override
    public List<CompanySimpleVo> findCompanyList() throws Exception {

        // 获取当前用户信息
        var user = UserContext.getUser();
        // 如果是系统管理员
        if (user.getIsAdmin()) {
            // 查询所有公司
            return companyDao.findAllCompanyList();
        }

        if (user.getCompanyId() == null) {
            throw CompanyException.companyNotExist();
        }

        // 查询当前用户所属公司
        Long companyId = user.getCompanyId();
        // 根据公司ID查询
        return companyDao.findCompanyList(companyId);
    }

    /**
     * 根据 id 查询公司信息
     *
     * @param id
     * @return
     */
    @Override
    public CompanyVo getById(Long id) throws Exception {

        Company company = companyDao.getById(id);
        if (company ==  null) {
            throw CompanyException.companyNotExist();
        }

        var companyVo = JSON.parseObject(JSON.toJSONString(company), CompanyVo.class);
        BeanConvertUtil.fieldConvert(company, companyVo);

        return companyVo;
    }

    /**
     * 分页查询公司列表
     *
     * @param companyName 公司名称
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return 分页结果
     */
    @Override
    public PageResult<CompanyPageVo> findByPage(String companyName, Integer pageNum, Integer pageSize) {

        // 构建分页对象
        Page<Company> page = MyBatisPlusPageUtils.buildPage(pageNum, pageSize);

        // 执行分页查询（会自动分页）
        Page<Company> usePage = companyDao.findByPage(page, companyName);

        // 将 MyBatis-Plus 的 IPage 转换为统一的 PageResult
        PageResult<Company> result = MyBatisPlusPageUtils.toPageResult(usePage);
        result.setList(usePage.getRecords());

        // 数据模型转换 将 entity 转为 vo
        PageResult<CompanyPageVo> pageResult = new PageResult<>();
        pageResult.setTotal(result.getTotal());
        pageResult.setPages(result.getPages());
        pageResult.setPageNum(result.getPageNum());
        pageResult.setPageSize(result.getPageSize());

        List<CompanyPageVo> voList = new ArrayList<>();
        if (result.getList() != null && result.getList().size() > 0) {
            for (Company company : result.getList()) {
                var companyPageVo = JSON.parseObject(JSON.toJSONString(company), CompanyPageVo.class);
                BeanConvertUtil.fieldConvert(company, companyPageVo);
                voList.add(companyPageVo);
            }
        }
        pageResult.setList(voList);

        return pageResult;
    }

    @Override
    public Boolean update(CompanyUpdateDto updateDto) throws Exception {

        // 根据ID查询
        Company companyDB = companyDao.getById(updateDto.getId());
        if (companyDB == null) {
            throw CompanyException.companyNotExist();
        }

        // Dao层修改
        Company company = JSON.parseObject(JSON.toJSONString(updateDto), Company.class);
        company.setUpdateTime(LocalDateTime.now());
        company.setUpdateBy(UserContext.getUserId());
        return companyDao.updateCompany(company) > 0;
    }

    /**
     * 添加公司
     * @param companyDto 数据模型
     * @return true:添加成功,false:添加失败
     */
    @Override
    public Boolean add(CompanyAddDto companyDto) throws Exception {

        // 公司编码不能重复
        if (companyDao.getCompanyByCode(companyDto.getCompanyCode()) != null) {
            throw CompanyException.repeatCompanyCode();
        }

        // 公司名称不能重复
        if (companyDao.getCompanyByName(companyDto.getCompanyName()) != null) {
            throw CompanyException.repeatCompanyName();
        }

        var company = JSON.parseObject(JSON.toJSONString(companyDto), Company.class);

        company.setId(snowflakeIdGenerator.nextId());

        return companyDao.addCompany(company) > 0;
    }
}




